<template>
  <div class="reviews-container">
    <!-- Back Navigation Header -->
    <div class="nav-header">
      <div class="back-button" @click="goBack">
        <van-icon name="arrow-left" size="20" />
      </div>
      <div class="header-title">用户评价 ({{ product.reviewCount }})</div>
      <div class="header-right"></div>
    </div>

    <!-- Rating Summary -->
    <div class="rating-summary">
      <div class="rating-overall">
        <div class="rating-score">{{ product.rating }}</div>
        <div class="rating-stars">
          <van-rate v-model="product.rating" readonly allow-half void-icon="star" void-color="#eee" />
        </div>
        <div class="rating-count">{{ product.reviewCount }}条评价</div>
      </div>
      
      <div class="rating-tags">
        <div 
          v-for="(tag, index) in reviewTags" 
          :key="index"
          class="rating-tag"
          :class="{ 'active': selectedTag === tag.name }"
          @click="filterByTag(tag.name)"
        >
          {{ tag.name }} ({{ tag.count }})
        </div>
      </div>
    </div>

    <!-- Filter Options -->
    <div class="filter-options">
      <div 
        class="filter-option" 
        :class="{ 'active': filterOption === 'all' }"
        @click="filterOption = 'all'"
      >
        全部
      </div>
      <div 
        class="filter-option" 
        :class="{ 'active': filterOption === 'withPhotos' }"
        @click="filterOption = 'withPhotos'"
      >
        有图 ({{ reviewsWithPhotos.length }})
      </div>
      <div 
        class="filter-option" 
        :class="{ 'active': filterOption === 'withVideos' }"
        @click="filterOption = 'withVideos'"
      >
        有视频 ({{ reviewsWithVideos.length }})
      </div>
    </div>

    <!-- Reviews List -->
    <div class="reviews-list">
      <div 
        v-for="(review, index) in filteredReviews" 
        :key="`review-${index}`"
        class="review-item"
      >
        <div class="review-header">
          <div class="reviewer-info">
            <img :src="review.avatar" :alt="review.username" class="reviewer-avatar" />
            <div class="reviewer-details">
              <div class="reviewer-name">{{ review.username }}</div>
              <div class="review-date">{{ review.date }}</div>
            </div>
          </div>
          <div class="review-rating">
            <van-rate v-model="review.rating" readonly void-icon="star" void-color="#eee" size="12" />
          </div>
        </div>
        
        <div class="review-content">{{ review.content }}</div>
        
        <div class="review-images" v-if="review.images && review.images.length > 0">
          <div 
            v-for="(image, imgIndex) in review.images" 
            :key="`review-img-${index}-${imgIndex}`" 
            class="review-image-container"
            @click="showGallery(review.images, imgIndex)"
          >
            <img :src="image" class="review-image" />
          </div>
        </div>
        
        <div class="review-video" v-if="review.video">
          <div class="video-thumbnail" @click="playVideo(review.video)">
            <img :src="review.videoThumbnail" alt="Video thumbnail" />
            <div class="play-icon">
              <van-icon name="play-circle-o" size="36" />
            </div>
          </div>
        </div>
        
        <div class="product-specs" v-if="review.specs">
          <van-tag plain type="primary">{{ review.specs }}</van-tag>
        </div>
        
        <div class="review-actions">
          <div class="action-button" @click="likeReview(index)">
            <van-icon :name="review.liked ? 'like' : 'like-o'" />
            <span>{{ review.likes || 0 }}</span>
          </div>
          <div class="action-button" @click="showCommentInput(index)">
            <van-icon name="comment-o" />
            <span>{{ review.comments ? review.comments.length : 0 }}</span>
          </div>
        </div>
        
        <!-- Comments Section -->
        <div class="review-comments" v-if="review.comments && review.comments.length > 0">
          <div 
            v-for="(comment, commentIndex) in review.comments.slice(0, showAllComments[index] ? undefined : 2)" 
            :key="`comment-${index}-${commentIndex}`"
            class="comment-item"
          >
            <span class="comment-username">{{ comment.username }}:</span>
            <span class="comment-content">{{ comment.content }}</span>
          </div>
          
          <div 
            v-if="review.comments.length > 2 && !showAllComments[index]" 
            class="view-more-comments"
            @click="showAllComments[index] = true"
          >
            查看全部{{ review.comments.length }}条回复
          </div>
        </div>
        
        <!-- Comment Input (conditionally shown) -->
        <div class="comment-input-container" v-if="activeCommentIndex === index">
          <van-field
            v-model="newComment"
            placeholder="添加评论..."
            class="comment-input"
          >
            <template #button>
              <van-button size="small" type="primary" @click="submitComment(index)">发送</van-button>
            </template>
          </van-field>
        </div>
      </div>
    </div>

    <!-- Image Gallery Popup -->
    <van-image-preview
      v-model:show="showImagePreview"
      :images="galleryImages"
      :start-position="galleryStartPosition"
      :show-index="true"
      :closeable="true"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()
const route = useRoute()
const productId = route.params.id

// State variables
const filterOption = ref('all')
const selectedTag = ref('')
const showImagePreview = ref(false)
const galleryImages = ref([])
const galleryStartPosition = ref(0)
const activeCommentIndex = ref(-1)
const newComment = ref('')
const showAllComments = ref({})

// Product data (mock)
const product = ref({
  id: productId || '1',
  name: 'Quantum Chronograph Watch - Limited Edition',
  rating: 4.8,
  reviewCount: 245
})

// Review tags (mock)
const reviewTags = ref([
  { name: '质量好', count: 156 },
  { name: '做工精细', count: 132 },
  { name: '外观漂亮', count: 98 },
  { name: '性价比高', count: 87 },
  { name: '佩戴舒适', count: 76 },
  { name: '走时准确', count: 65 },
  { name: '包装精美', count: 54 },
  { name: '客服好', count: 43 }
])

// Reviews data (mock)
const reviews = ref([
  {
    username: '王小明',
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    rating: 5,
    content: '手表质量非常好，做工精细，走时准确。包装也很精美，很适合送礼。客服态度也很好，有问题都及时解答。',
    images: [
      'https://images.unsplash.com/photo-1539874754764-5a96559165b0?q=80&w=500&auto=format&fit=crop',
      'https://images.unsplash.com/photo-1434056886845-dac89ffe9b56?q=80&w=500&auto=format&fit=crop'
    ],
    date: '2023-12-15',
    specs: '银色, 42mm',
    likes: 24,
    liked: false,
    comments: [
      { username: '客服小李', content: '感谢您的支持，祝您使用愉快！' },
      { username: '张三', content: '请问走时准确吗？有没有偏差？' },
      { username: '王小明', content: '非常准确，一天误差不到1秒' }
    ]
  },
  {
    username: '李小红',
    avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
    rating: 4,
    content: '整体来说不错，但是表带有点硬，需要一段时间适应。表盘设计很漂亮，夜光效果也很好。',
    images: [],
    date: '2023-11-28',
    specs: '黑色, 40mm',
    likes: 12,
    liked: false,
    comments: []
  },
  {
    username: '张大山',
    avatar: 'https://randomuser.me/api/portraits/men/22.jpg',
    rating: 5,
    content: '这款手表真的超出我的预期，机械感十足，走时也很准。朋友们看到都很羡慕，问我在哪买的。强烈推荐给喜欢机械表的朋友。',
    images: [
      'https://images.unsplash.com/photo-1508057198894-247b23fe5ade?q=80&w=500&auto=format&fit=crop'
    ],
    video: 'https://example.com/video1.mp4',
    videoThumbnail: 'https://images.unsplash.com/photo-1508057198894-247b23fe5ade?q=80&w=500&auto=format&fit=crop',
    date: '2023-11-15',
    specs: '银色, 44mm',
    likes: 36,
    liked: false,
    comments: [
      { username: '刘先生', content: '请问防水效果怎么样？' },
      { username: '张大山', content: '防水效果很好，我游泳时戴着都没问题' }
    ]
  },
  {
    username: '陈小姐',
    avatar: 'https://randomuser.me/api/portraits/women/29.jpg',
    rating: 3,
    content: '手表本身不错，但是送货太慢了，等了将近两周才收到。包装有点简陋，好在产品没有损坏。',
    images: [],
    date: '2023-10-30',
    specs: '金色, 40mm',
    likes: 5,
    liked: false,
    comments: [
      { username: '客服小王', content: '非常抱歉给您带来不便，我们会改进物流服务。' }
    ]
  },
  {
    username: '赵先生',
    avatar: 'https://randomuser.me/api/portraits/men/62.jpg',
    rating: 5,
    content: '作为一个表迷，我对这款手表的评价是：性价比极高！机芯走时稳定，外观设计经典大气，佩戴舒适。最重要的是价格很实惠，同等品质的瑞士表要贵一倍以上。',
    images: [
      'https://images.unsplash.com/photo-1522312346375-d1a52e2b99b3?q=80&w=500&auto=format&fit=crop',
      'https://images.unsplash.com/photo-1523275335684-37898b6baf30?q=80&w=500&auto=format&fit=crop'
    ],
    date: '2023-10-22',
    specs: '银色, 42mm',
    likes: 48,
    liked: false,
    comments: []
  }
])

// Computed properties
const reviewsWithPhotos = computed(() => {
  return reviews.value.filter(review => review.images && review.images.length > 0)
})

const reviewsWithVideos = computed(() => {
  return reviews.value.filter(review => review.video)
})

const filteredReviews = computed(() => {
  let result = [...reviews.value]
  
  // Apply tag filter
  if (selectedTag.value) {
    result = result.filter(review => review.content.includes(selectedTag.value))
  }
  
  // Apply media filter
  if (filterOption.value === 'withPhotos') {
    result = result.filter(review => review.images && review.images.length > 0)
  } else if (filterOption.value === 'withVideos') {
    result = result.filter(review => review.video)
  }
  
  return result
})

// Initialize comment visibility state
onMounted(() => {
  reviews.value.forEach((_, index) => {
    showAllComments.value[index] = false
  })
})

// Methods
const goBack = () => {
  router.back()
}

const filterByTag = (tag) => {
  if (selectedTag.value === tag) {
    selectedTag.value = ''
  } else {
    selectedTag.value = tag
  }
}

const showGallery = (images, startIndex) => {
  galleryImages.value = images
  galleryStartPosition.value = startIndex
  showImagePreview.value = true
}

const playVideo = (videoUrl) => {
  showToast('视频播放功能即将上线')
  console.log('Playing video:', videoUrl)
}

const likeReview = (index) => {
  const review = reviews.value[index]
  if (!review.liked) {
    review.likes = (review.likes || 0) + 1
    review.liked = true
  } else {
    review.likes = review.likes - 1
    review.liked = false
  }
}

const showCommentInput = (index) => {
  if (activeCommentIndex.value === index) {
    activeCommentIndex.value = -1
  } else {
    activeCommentIndex.value = index
    newComment.value = ''
  }
}

const submitComment = (index) => {
  if (!newComment.value.trim()) {
    showToast('评论内容不能为空')
    return
  }
  
  const review = reviews.value[index]
  if (!review.comments) {
    review.comments = []
  }
  
  review.comments.push({
    username: '我',
    content: newComment.value.trim()
  })
  
  newComment.value = ''
  activeCommentIndex.value = -1
  showToast('评论发布成功')
}
</script>

<style scoped>
.reviews-container {
  padding-bottom: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* Navigation Header */
.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: white;
  z-index: 100;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.back-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.header-right {
  width: 32px;
}

/* Rating Summary */
.rating-summary {
  margin-top: 56px;
  padding: 20px 16px;
  background-color: white;
}

.rating-overall {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.rating-score {
  font-size: 36px;
  font-weight: 700;
  color: #ff9500;
}

.rating-stars {
  margin: 8px 0;
}

.rating-count {
  font-size: 14px;
  color: #969799;
}

.rating-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.rating-tag {
  padding: 6px 12px;
  background-color: #f2f3f5;
  border-radius: 16px;
  font-size: 13px;
  color: #646566;
}

.rating-tag.active {
  background-color: #ecf5ff;
  color: #1989fa;
}

/* Filter Options */
.filter-options {
  display: flex;
  padding: 12px 16px;
  background-color: white;
  margin-top: 1px;
  border-bottom: 1px solid #f2f3f5;
}

.filter-option {
  margin-right: 24px;
  font-size: 14px;
  color: #646566;
  position: relative;
}

.filter-option.active {
  color: #323233;
  font-weight: 500;
}

.filter-option.active::after {
  content: '';
  position: absolute;
  bottom: -12px;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #1989fa;
}

/* Reviews List */
.reviews-list {
  padding: 0 16px;
}

.review-item {
  margin-top: 12px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.reviewer-info {
  display: flex;
  align-items: center;
}

.reviewer-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
}

.reviewer-details {
  display: flex;
  flex-direction: column;
}

.reviewer-name {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
}

.review-date {
  font-size: 12px;
  color: #969799;
  margin-top: 2px;
}

.review-content {
  font-size: 14px;
  color: #323233;
  line-height: 1.6;
  margin-bottom: 12px;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.review-image-container {
  width: calc(33.333% - 6px);
  aspect-ratio: 1;
  overflow: hidden;
  border-radius: 4px;
}

.review-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.review-video {
  margin-bottom: 12px;
}

.video-thumbnail {
  position: relative;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.video-thumbnail img {
  width: 100%;
  aspect-ratio: 16/9;
  object-fit: cover;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.product-specs {
  margin-bottom: 12px;
}

.review-actions {
  display: flex;
  border-top: 1px solid #f2f3f5;
  padding-top: 12px;
}

.action-button {
  display: flex;
  align-items: center;
  margin-right: 24px;
  font-size: 14px;
  color: #646566;
}

.action-button .van-icon {
  margin-right: 4px;
}

.review-comments {
  margin-top: 12px;
  padding: 12px;
  background-color: #f7f8fa;
  border-radius: 4px;
}

.comment-item {
  font-size: 13px;
  margin-bottom: 8px;
}

.comment-item:last-child {
  margin-bottom: 0;
}

.comment-username {
  font-weight: 500;
  color: #323233;
}

.comment-content {
  color: #646566;
}

.view-more-comments {
  font-size: 13px;
  color: #1989fa;
  margin-top: 8px;
}

.comment-input-container {
  margin-top: 12px;
}

.comment-input {
  background-color: #f7f8fa;
  border-radius: 4px;
}
</style>